package com.demo.java.config;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalException {

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object paramValidHandler(MethodArgumentNotValidException ex) {
        ex.printStackTrace();
        StringBuilder sb = new StringBuilder();
        final BindingResult result = ex.getBindingResult();
        result.getFieldErrors().stream().forEach(x -> sb.append(x.getDefaultMessage()));
        return "{\"code\": 100000, \"status\": \"failed\", \"msg\": \"" + sb.toString() + " !\"}";
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Object exceptionHandler(Exception ex) {
        return "{\"code\": 100000, \"status\": \"failed\", \"msg\": " + ex.getMessage() + "}";
    }
}
